﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Configuration;

namespace Ubatic.Services
{
    public class EmailService
    {
        public string Subject { get; set; }
        public string From { get; set; }
        public string ReplayTo { get; set; }
        public string Body { get; set; }
        public string Host { get; set; }
        public string Port { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool EnableSSL { get; set; }
        public bool DefaultCredentials { get; set; }

        private string _BodyPath { get; set; }
        public string BodyPath { get { return _BodyPath; } }

        public void LoadFromConfig()
        {
            Subject = ConfigurationManager.AppSettings["MailSubject"];
            From = ConfigurationManager.AppSettings["MailFrom"];
            ReplayTo = ConfigurationManager.AppSettings["MailReplayTo"];
            _BodyPath = ConfigurationManager.AppSettings["MailBodyPathHtml"];

            Host = ConfigurationManager.AppSettings["MailHost"];
            Port = ConfigurationManager.AppSettings["MailPort"];
            UserName = ConfigurationManager.AppSettings["MailUserName"];
            Password = ConfigurationManager.AppSettings["MailPassword"];
            EnableSSL = bool.Parse(ConfigurationManager.AppSettings["MailEnableSSL"]);
            DefaultCredentials = bool.Parse(ConfigurationManager.AppSettings["MailDefaultCredentials"]);
        }

        public void SendEmail(string emailAddressTo)
        {
            MailMessage email = new MailMessage();
            email.To.Add(new MailAddress(emailAddressTo));
            email.Subject = Subject;
            email.Body = Body;
            email.From = new MailAddress(From);
            email.ReplyToList.Add(new MailAddress(ReplayTo));
            //email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
            email.IsBodyHtml = true;

            SmtpClient client = new SmtpClient();
            client.Host = Host;
            client.Port = Convert.ToInt32(Port);
            client.EnableSsl = EnableSSL;

            client.UseDefaultCredentials = DefaultCredentials;
            if (!String.IsNullOrEmpty(UserName))
            {
                client.Credentials = new NetworkCredential(UserName, Password);
            }

            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Send(email);
        }
    }
}
